﻿using HenuAlbum.ControllerModels;
using HenuAlbum.DbContext;
using HenuAlbum.Identity;
using HenuAlbum.Models;
using HenuAlbum.ResponseModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace HenuAlbum.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SchoolController : ControllerBase
    {
        private readonly AppDbContext _appDbContext;

        private readonly UserManager<User> _userManager;

        public SchoolController(AppDbContext appDbContext, UserManager<User> userManager)
        {
            _appDbContext = appDbContext;
            _userManager = userManager;
        }

        [HttpGet("Grades")]
        public async Task<IActionResult> GetGrades()
        {
            var list = await _appDbContext.Grades
                .AsNoTracking()
                .Select(x => new { x.Id, x.Value, x.Display })
                .ToListAsync();
            return Ok(new ArrayResponse(list));
        }

        [Authorize]
        [Authorize(Roles = "管理员")]
        [HttpPost("AddGrade")]
        public async Task<IActionResult> AddGrade(AddGradeParam param)
        {
            if (_appDbContext.Grades.Any(x => x.Value == param.Grade))
            {
                return BadRequest(new AlreadyExistsError("该年级已经存在!"));
            }
            var grade = new Grade() { Value = param.Grade };
            _appDbContext.Grades.Add(grade);
            foreach (var college in _appDbContext.Colleges.Include(x => x.Majors).ToList())
            {
                foreach (var major in college.Majors)
                {
                    major.Classes.Add(new Class() { Name = "默认班级", Grade = grade });
                }
            }
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }

        [Authorize]
        [Authorize(Roles = "管理员")]
        [HttpPost("RemoveGrade")]
        public async Task<IActionResult> RemoveGrade(RemoveGradeParam param)
        {
            var grade = await _appDbContext.Grades.Where(x => x.Id == param.GradeId).FirstOrDefaultAsync();
            if (grade == null)
            {
                return BadRequest(new NotExistsError("该年级不存在!"));
            }
            _appDbContext.Grades.Remove(grade);
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }

        [HttpGet("Colleges")]
        public async Task<IActionResult> GetColleges()
        {
            var list = await _appDbContext.Colleges
                .AsNoTracking()
                .Select(x => new { x.Id, x.Name })
                .ToListAsync();
            return Ok(new ArrayResponse(list));
        }

        [HttpGet("Majors")]
        public async Task<IActionResult> GetMajors(int collegeId)
        {
            var list = await _appDbContext.Majors
                .AsNoTracking()
                .Where(x => x.CollegeId == collegeId)
                .Select(x => new { x.Id, x.Name })
                .ToListAsync();
            return Ok(new ArrayResponse(list));
        }

        [HttpGet("Classes")]
        public async Task<IActionResult> GetClasses(int gradeId, int majorId)
        {
            var list = await _appDbContext.Classes
                .AsNoTracking()
                .Include(x => x.Grade)
                .Where(x => x.MajorId == majorId && x.GradeId == gradeId)
                .Select(x => new
                {
                    x.Id,
                    x.Name,
                    Grade = new { x.Grade.Id, x.Grade.Display, x.Grade.Value }
                })
                .ToListAsync();
            return Ok(new ArrayResponse(list));
        }

        [HttpGet("QueryClasses")]
        [Authorize(Roles = "管理员, 辅导员")]
        public async Task<IActionResult> QueryClasses(int gradeId, int majorId)
        {
            var list = await _appDbContext.Classes
                .AsNoTracking()
                .Include(x => x.Grade)
                .Where(x => x.MajorId == majorId && x.GradeId == gradeId)
                .Select(x => new
                {
                    x.Id,
                    x.Name,
                    Grade = new { x.Grade.Id, x.Grade.Display, x.Grade.Value },
                    StudentCount = _appDbContext.Users.AsNoTracking().Count(u => u.ClassId == x.Id),
                    AlbumCount = _appDbContext.PersonalAlbums.AsNoTracking().Count(a => a.ClassId == x.Id) + _appDbContext.GroupAlbums.AsNoTracking().Count(a => a.ClassId == x.Id)
                })
                .ToListAsync();
            return Ok(new ArrayResponse(list));
        }

        [Authorize]
        [Authorize(Roles = "管理员, 辅导员")]
        [HttpPost("AddClass")]
        public async Task<IActionResult> AddClass(AddClassParams param)
        {
            Major major = null;
            if (User.IsInRole("辅导员"))
            {
                var useridstr = User.FindFirstValue(ClaimTypes.NameIdentifier);
                int userid = int.Parse(useridstr);
                //这里没有做连接查询查到的major一直为空，已经修改了
                var user = await _appDbContext.Users.Include(x => x.ManagedMajors).Where(x => x.Id == userid).FirstOrDefaultAsync();

                major = user.ManagedMajors.Where(x => x.Id == param.MajorId).FirstOrDefault();
            }
            else
            {
                major = await _appDbContext.Majors.Include(x => x.Classes).Where(x => x.Id == param.MajorId).FirstOrDefaultAsync();
            }

            if (major == null)
            {
                return BadRequest(new NotExistsError("专业不存在!"));
            }
            if (major.Classes.Any(x => x.Name == param.ClassName))
            {
                return BadRequest(new AlreadyExistsError("该班级已经存在!"));
            }
            major.Classes.Add(new Class() { Name = param.ClassName, GradeId = param.GradeId });
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }

        [Authorize(Roles = "管理员, 辅导员")]
        [HttpPost("RemoveClass")]
        public async Task<IActionResult> RemoveClass(RemoveClassParams param)
        {
            var theClass = await _appDbContext.Classes
                .Include(x => x.Major)
                .Where(x => x.Id == param.ClassId)
                .FirstOrDefaultAsync();
            if (theClass == null)
            {
                return BadRequest(new NotExistsError("班级不存在!"));
            }

            if (User.IsInRole("辅导员"))
            {
                var userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
                var user = await _appDbContext.Users
                    .AsNoTracking()
                    .Include(x => x.ManagedMajors)
                    .Where(x => x.Id == userId)
                    .FirstOrDefaultAsync();
                if (!user.ManagedMajors.Any(x => x.Id == theClass.MajorId))
                {
                    return BadRequest(new NotExistsError("班级不存在!"));
                }
            }

            _appDbContext.Classes.Remove(theClass);
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }

    }
}
